package servlet;

import model.User;
import service.UserService;
import service.impl.UserServiceImpl;
import utils.BaseServlet;
import utils.DaoUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;


@WebServlet("/user_all.do")
public class UserlistServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        //获取请求参数
        String method = req.getParameter("method");
        if (null == method) {
            //查询所有商品
            list(req, resp);
        } else if ("del".equals(method)) {
            //查看商品详情
            del(req, resp);
        }else if ("add".equals(method)){
            add(req,resp);
        }else if ("update".equals(method)){
            update(req,resp);
        }


    }

    private void update(HttpServletRequest req, HttpServletResponse resp) {
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String Id = req.getParameter("id");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        User user = new User(Integer.parseInt(Id),name,password,phone,email);
        boolean flag = userService.add(user);
        resp.setContentType("text/plain;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        if(flag){
            out.write("true");
            HttpSession session = req.getSession();
            session.setAttribute("user",user);
            resp.sendRedirect("user_add.jsp");
        }else{
            out.write("false");
        }
        out.close();
    }

    private void del(HttpServletRequest req, HttpServletResponse resp) throws IOException{


    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        List<User> users = userService.findAllUser();
        //将产品集合放入会话中
        session.setAttribute("User", users);
        //页面重定向
        resp.sendRedirect("user_all.jsp");
    }
}